<template>
    <div class="app-container">
        <br>
        <!--搜索条件-->
        <el-row>
            <el-form>
                <el-col :span="9">
                    <el-form-item label="关键字">
                        <el-input v-model="searchObj.query" placeholder="商品参数" style="width: 280px;"
                                  clearable
                        ></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="分类">
                        <el-cascader :options="categories"
                                     :props="{ value: 'id', label: 'name' }"
                                     @change="handleSearchChange"
                                     v-model="searchObj.categoryId"
                                     :show-all-levels="false"
                                     placeholder="请选择商品分类"
                        ></el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="6" style="min-height:1px;"></el-col>
                <el-col :span="6">
                    <el-button icon="el-icon-refresh" @click="reset"
                               style="float: right;margin-left: 10px;"
                    >重置
                    </el-button>
                    <el-button type="primary" icon="el-icon-search" @click="getBooks"
                               style="float: right;"
                    >搜索
                    </el-button>
                </el-col>
            </el-form>
        </el-row>

        <el-divider></el-divider>

        <!-- 操作 -->
        <el-row style="margin-bottom: 20px;">
            <el-button type="danger" plain icon="el-icon-delete" @click="deleteBatchByIds"
                       :disabled="multipleSelection.length === 0"
                       style="float: right;margin-left: 10px;"
            >批量删除
            </el-button>
            <el-button type="success" plain icon="el-icon-plus" @click="add" style="float: right;">添加
            </el-button>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loading" :data="books" stripe border style="width: 100%;margin-top: 10px;"
                  @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="40" align="center"/>

            <el-table-column label="序号" width="70" align="center">
                <template slot-scope="scope">
                    {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>

            <el-table-column prop="name" label="书名" align="center"/>
            <el-table-column label="封面" align="center">
                <template slot-scope="scope">
                    <el-image v-if="'cover' in scope.row" :src="scope.row.cover" fit="fit"
                              style="height: 80px;"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="详情" align="center"/>
            <el-table-column prop="author" label="作者" align="center"/>
            <el-table-column prop="publisher" label="出版社" align="center"/>
            <el-table-column prop="price" label="价格" align="center"/>
            <el-table-column prop="storeNum" label="库存" align="center"/>
            <el-table-column prop="status" label="状态" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.status === 0">上架</el-tag>
                    <el-tag type="danger" v-else-if="scope.row.status === 1">下架</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="类别" align="center"/>

            <el-table-column label="操作" align="center" width="280">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" @click="edit(scope.row.id)" style="color: #DCA550">修改</el-button>
                    <el-button type="text" icon="el-icon-delete" @click="removeBook(scope.row.id)" style="color:#E47370;">删除</el-button>
                    <el-button type="text" v-if="scope.row.status === 0" icon="el-icon-bottom" style="color: #919398"
                               @click="updateStatus(scope.row.id, scope.row.status, scope.row.name)"
                    >下架
                    </el-button>
                    <el-button type="text" v-else-if="scope.row.status === 1" icon="el-icon-top" style="color: #5A9CF8"
                               @click="updateStatus(scope.row.id, scope.row.status, scope.row.name)"
                    >上架
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-divider></el-divider>
        <!-- 分页组件 -->
        <el-pagination :page-size.sync="pageSize" layout="total, sizes, prev, pager, next, jumper"
                       :total="total" :page-sizes="[5,10, 20, 30, 40]" :current-page.sync="pageNum"
                       @current-change="getBooks"
                       @size-change="getBooks"/>

        <!-- 新增或者修改图书信息弹窗 -->
        <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
            <el-form :rules="rules" ref="dataForm" :model="book" label-width="150px" size="small"
                     style="padding-right: 40px;"
            >
                <el-form-item label="图书名称" prop="name">
                    <el-input v-model="book.name"/>
                </el-form-item>

                <el-form-item label="图书封面" prop="cover">
                    <el-upload class="avatar-uploader" :action="uploadURL" name="img" :show-file-list="false"
                               :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="token"
                    >
                        <img v-if="book.cover" :src="book.cover" class="avatar" :alt="book.name">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div style="font-size:xx-small;">点击上传图书封面，只能上传jpg/png文件，且不超过10MB</div>
                </el-form-item>

                <el-form-item label="图书详情">
                    <el-input v-model="book.description"/>
                </el-form-item>

                <el-form-item label="图书作者" prop="author">
                    <el-input v-model="book.author"/>
                </el-form-item>

                <el-form-item label="图书出版社" prop="publisher">
                    <el-input v-model="book.publisher"/>
                </el-form-item>

                <el-form-item label="图书价格">
                    <el-input v-model="book.price" type="number" min="0"/>
                </el-form-item>

                <el-form-item label="图书库存">
                    <el-input v-model="book.storeNum" type="number" min="0"/>
                </el-form-item>

                <el-form-item label="图书分类">
                    <div class="block">
                        <el-cascader :options="categories"
                                     :props="{ value: 'id', label: 'name' }"
                                     @change="handleInsertOrUpdateChange"
                                     v-model="book.categoryId"
                                     :show-all-levels="false"
                        ></el-cascader>
                    </div>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
                <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getPageBook,
    addBook,
    deleteBookById,
    getBookById,
    updateBookStatus,
    deleteBatchByIds,
    updateBook
} from '@/api/book'
import { getAllCategory } from '@/api/category'

export default {
    name: 'Book',
    data() {
        return {
            pageNum: 1,
            pageSize: 5,
            total: 0,
            searchObj: {},
            loading: true,
            book: {},
            books: [],
            multipleSelection: [],
            categories: [],
            title: '',
            dialogVisible: false,
            rules: {
                name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
                author: [{ required: true, message: '商品作者不能为空', trigger: 'blur' }],
                publisher: [{ required: true, message: '商品制造商不能为空', trigger: 'blur' }]
            },
            token: {
                token: ''
            },
            uploadURL: 'http://localhost:3315/admin/upload'
        }
    },
    methods: {

        // 点击添加按钮
        add() {
            this.title = '新增商品'
            this.book = {}
            this.dialogVisible = true
        },

        // 点击批量删除
        deleteBatchByIds() {
            const length = this.multipleSelection.length
            this.$confirm('此操作将永久删除这' + length + '件商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteBatchByIds(this.multipleSelection).then(response => {
                    if (response.code === 200) {
                        this.$message.success('批量删除成功')
                        if ((this.total - this.multipleSelection.length) % this.pageSize === 0) {
                            this.pageNum -= 1
                            getPageBook(this.pageNum, this.pageSize, this.searchObj).then(response => {
                                this.books = response.data.list
                                this.total = response.data.total
                            })
                        } else {
                            this.getBooks()
                        }
                    } else {
                        this.$message.error("当前商品存在于别的用户的订单子项中,暂时无法删除")
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 点击编辑按钮
        edit(id) {
            // 图书数据回显
            getBookById(id).then(response => {
                if (response.code === 200) {
                    this.title = '修改图书'
                    this.book = response.data
                    this.dialogVisible = true
                } else {
                    this.$message.error(response.message)
                }
            })
        },

        // 点击删除按钮
        removeBook(id) {
            this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteBookById(id).then(response => {
                    if (response.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        // 如果是当前页的唯一一条数据，则删除时自动跳转到前一页
                        if (this.total % this.pageSize === 1) {
                            this.pageNum -= 1
                            getPageBook(this.pageNum, this.pageSize, this.searchObj).then(response => {
                                this.books = response.data.list
                                this.total = response.data.total
                            })
                        } else {
                            this.getBooks()
                        }

                    } else {
                        this.$message.error(response.message)
                    }
                })
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },

        // 获取图书列表
        getBooks() {
            getPageBook(this.pageNum, this.pageSize, this.searchObj).then(response => {
                this.books = response.data.list
                this.total = response.data.total
                this.loading = false
            })
        },

        // 下拉框获取分类信息
        getCategories() {
            getAllCategory().then(response => {
                this.categories = this.getTreeData(response.data)
            })
        },

        // 点击重置按钮
        reset() {
            this.searchObj = {}
            this.getBooks()
        },

        // 点击弹出框的保存按钮
        saveOrUpdate() {
            // 参数校验
            this.$refs.dataForm.validate((valid) => {
                // 校验成功
                if (valid) {
                    // 根据是否传递id属性判断是修改还是添加
                    if (!this.book.id) {
                        // 添加图书
                        this.saveBook()
                    } else {
                        // 修改图书
                        this.modifyBook()
                    }
                } else {
                    this.$message.error('指定参数不能为空！')
                    return false
                }
            })
        },

        // 保存商品的方法
        saveBook() {
            addBook(this.book).then(response => {
                if (response.code === 200) {
                    this.$message.success('添加商品信息成功')
                    this.dialogVisible = false
                    this.book = {}
                    this.getBooks()
                } else {
                    this.$message.error(response.message || '添加失败，请重试')
                }
            })
        },

        // 修改商品信息
        modifyBook() {
            updateBook(this.book).then(response => {
                if (response.code === 200) {
                    this.$message.success('修改商品信息成功')
                    this.dialogVisible = false
                    this.book = {}
                    this.getBooks()
                } else {
                    this.$message.error(response.message || '修改失败，请重试')
                }
            })
        },

        // 点击下/上架按钮
        updateStatus(id, curStatus, name) {
            let status = 0
            let msg = ''
            if (curStatus === 0) {
                msg = '确定要下架《' + name + '》吗？'
                status = 1
            } else {
                msg = '确定要上架《' + name + '》吗？'
            }
            this.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                updateBookStatus(id, status).then(response => {
                    if (response.code === 200) {
                        if (status === 0) {
                            this.$message.success('上架成功')
                        } else {
                            this.$message.success('下架成功')
                        }
                        this.getBooks()
                    } else {
                        this.$message.error('修改状态失败，请刷新页面重试')
                    }
                })
            }).catch(() => {
                this.$message.info('已取消该操作')
            })
        },
        // 搜索时，分类下拉框数据改变回调
        handleSearchChange(value) {
            if (value) {
                this.searchObj.categoryId = value[value.length - 1]
            }
        },

        // 新增/修改时，分类下拉框数据改变回调
        handleInsertOrUpdateChange(value) {
            if (value) {
                this.book.categoryId = value[value.length - 1]
            }
        },

        // 批量删除获取选择的记录编号
        handleSelectionChange(selection) {
            this.multipleSelection = selection.map(item => {
                return item.id
            })
        },

        // 图片上传成功回调
        handleAvatarSuccess(res) {//上传封面
            if (res.code === 200) {
                this.book.cover = res.data
                this.$notify({
                    title: '操作成功',
                    message: '图书封面上传成功',
                    type: 'success'
                })
            } else {
                this.$notify.error({
                    title: '操作失败',
                    message: '图书封面上传失败，请稍后重试！'
                })
            }
        },

        // 上传图片前的检查工作
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpg' || 'image/png' || 'image/jpeg'
            const isLt2M = file.size / 1024 / 1024 < 10

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG或者PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },

        // 处理后断传递过来的树形数据children为空的问题
        getTreeData(data = []) {
            if (data === []) {
                return false
            }
            for (let i = 0; i < data.length; i++) {
                if (data[i].children === undefined || data[i].children.length === 0) { /// 改成这样判断条件
                    // children若为空数组，则将children设为undefined
                    data[i].children = undefined
                } else {
                    // children若不为空数组，则继续 递归调用 本方法
                    this.getTreeData(data[i].children)
                }
            }
            return data
        }

    },
    created() {
        // 获取图书数据
        this.getBooks()
        this.getCategories()
        this.token.token = this.$store.getters.token
    }
}
</script>

<style>
.app-container {
    margin: 20px;
}

.el-form-item .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.el-form-item .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.el-upload .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
}

.avatar {
    height: 150px;
    display: block;
}
</style>
